<template>
  <div style="width: 100%">
    <el-button type="primary" @click="showAddDeviceDialog">新建设备</el-button>
    <el-table :data="baseData" style="width: 100%" height="calc(100vh - 230px)">
      <el-table-column prop="equipmentId" label="设备编码">
        <template #default="scope">
          <span>{{
            data.deviceOptions.find(
              (i) => i.id === scope.row.equipmentId
            )?.equipmentCode
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="equipmentId" label="设备名称">
        <template #default="scope">
          <span>{{
            data.deviceOptions.find(
              (i) => i.id === scope.row.equipmentId
            )?.equipmentName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="text" @click="editDevice(scope.row)">编辑</el-button>
          <el-button type="text" @click="deleteDevice(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新建设备弹窗 -->
    <el-dialog title="新建设备" v-model="data.showDeviceDialog">
      <el-select v-model="data.newDevice.equipmentId" placeholder="请选择设备名称">
        <el-option v-for="device in data.deviceOptions" :key="device.id"
        :label="`${device.equipmentCode} - ${device.equipmentName}`" 

          :value="device.id" />
      </el-select>
      <template #footer>
        <el-button @click="data.showDeviceDialog = false">取消</el-button>
        <el-button type="primary" @click="addDevice">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import axiosInstance from '@/utils/http/api';
import { onMounted, reactive, watch, ref } from 'vue';
import { ElMessageBox } from 'element-plus';


const data = reactive({
  showDeviceDialog: false,
  newDevice: { equipmentId: '' },
  deviceOptions: []
});
const baseData = ref([]);
const indexParenId = ref();

const props = defineProps({
  devicesData: Array,
  onSubmit: Function,
});

watch(props, (val) => {
  if (val.devicesData) {
    baseData.value = val.devicesData.equipment;
    indexParenId.value = val.devicesData.index;
    console.log(val, 'devicesData', baseData?.value);
  }
});

const showAddDeviceDialog = () => {
  data.showDeviceDialog = true;
  data.newDevice = {}
};

const getDeviceOptions = async () => {
  try {
    const response = await axiosInstance.post('/api/basedataEquipment/getAll', {});
    console.log(response.data);
    data.deviceOptions = response.data;
  } catch (error) {
    console.error('获取设备选项失败:', error);
  }
};
const replaceItemById = (items, newItem) => {
  const newData = items.map(i => {
    if (i.index_id === newItem.index_id) {
      return newItem;
    }
    return i
  })
  return newData

}

const addDevice = () => {
  let addData = []
  if (data.newDevice.index_id) {
    addData = replaceItemById(baseData?.value, data.newDevice)
  } else {
    const ids = Math.floor(Math.random() * 100)
    console.log(baseData.value, 'baseData.value')
    if (baseData.value) {
      addData = [...baseData.value, { ...data.newDevice, index_id: ids }]
    } else {
      addData = [{ ...data.newDevice, index_id: ids }]
    }

  }
  console.log(addData, 'addData ')
  if (props.onSubmit) {
    props.onSubmit(addData, 'equipment', indexParenId.value);
  }
  // data.newDevice.equipmentId = '';
  data.showDeviceDialog = false;
};

const editDevice = (row) => {
  console.log(row);
  data.newDevice = row;
  data.showDeviceDialog = true;
};

const deleteDevice = (row) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const delBaseData = baseData?.value.filter(i => i.index_id !== row.index_id)
    if (props.onSubmit) {
      props.onSubmit(delBaseData, 'equipment', indexParenId.value);
    }
  }).catch(() => {
  });

};

onMounted(() => {
  getDeviceOptions();
});
</script>

<style scoped>
.el-table {
  margin-top: 20px;
}
</style>
